<template>
  <div class="request-logs-container">
    <div class="page-header">
      <h2>请求历史记录</h2>
      <el-button type="danger" @click="clearAllLogs" :disabled="logs.length === 0">
        清空所有记录
      </el-button>
    </div>

    <el-card class="logs-card" shadow="never">
      <el-table
        v-loading="loading"
        :data="logs"
        style="width: 100%"
        border
        stripe
        @row-click="handleRowClick"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="method" label="请求方法" width="100">
          <template #default="{ row }">
            <el-tag
              :type="getMethodTagType(row.method)"
              size="small"
            >
              {{ row.method }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="path" label="请求路径" min-width="200" show-overflow-tooltip />
        <el-table-column prop="statusCode" label="状态码" width="100">
          <template #default="{ row }">
            <el-tag
              :type="getStatusTagType(row.statusCode)"
              size="small"
            >
              {{ row.statusCode }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="responseTime" label="响应时间" width="120">
          <template #default="{ row }">
            {{ row.responseTime }}ms
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="请求时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              link
              @click.stop="viewLogDetail(row.id)"
            >
              查看详情
            </el-button>
            <el-button
              type="danger"
              size="small"
              link
              @click.stop="deleteLog(row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container" v-if="logs.length > 0">
        <el-pagination
          background
          layout="prev, pager, next"
          :total="total"
          :page-size="pageSize"
          :current-page="currentPage"
          @current-change="handlePageChange"
        />
      </div>

      <el-empty v-if="logs.length === 0 && !loading" description="暂无请求记录" />
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessageBox, ElMessage } from 'element-plus'
import axios from 'axios'

const router = useRouter()
const logs = ref([])
const loading = ref(false)
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const searchQuery = ref('')

// 过滤后的日志列表
const filteredLogs = computed(() => {
  if (!searchQuery.value) return logs.value
  
  const query = searchQuery.value.toLowerCase()
  return logs.value.filter(log => 
    log.path.toLowerCase().includes(query) || 
    String(log.statusCode).includes(query) ||
    log.method.toLowerCase().includes(query)
  )
})

// 获取请求日志列表
const fetchLogs = async () => {
  loading.value = true
  try {
    const response = await axios.get('http://localhost:8080/api/logs')
    logs.value = response.data
    total.value = response.data.length
    loading.value = false
  } catch (error) {
    console.error('获取请求日志失败:', error)
    ElMessage.error('获取请求日志失败')
    loading.value = false
  }
}

// 格式化日期
const formatDate = (dateString) => {
  const date = new Date(dateString)
  return date.toLocaleString()
}

// 根据请求方法获取标签类型
const getMethodTagType = (method) => {
  const methodMap = {
    'GET': 'success',
    'POST': 'primary',
    'PUT': 'warning',
    'DELETE': 'danger',
    'PATCH': 'info'
  }
  return methodMap[method] || ''
}

// 根据状态码获取标签类型
const getStatusTagType = (statusCode) => {
  if (statusCode >= 200 && statusCode < 300) {
    return 'success'
  } else if (statusCode >= 300 && statusCode < 400) {
    return 'info'
  } else if (statusCode >= 400 && statusCode < 500) {
    return 'warning'
  } else {
    return 'danger'
  }
}

// 查看日志详情
const viewLogDetail = (id) => {
  router.push(`/logs/${id}`)
}

// 删除单条日志
const deleteLog = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除这条请求记录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await axios.delete(`http://localhost:8080/api/logs/${id}`)
    ElMessage.success('删除成功')
    fetchLogs()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除请求日志失败:', error)
      ElMessage.error('删除请求日志失败')
    }
  }
}

// 清空所有日志
const clearAllLogs = async () => {
  try {
    await ElMessageBox.confirm('确定要清空所有请求记录吗？此操作不可恢复！', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await axios.delete('http://localhost:8080/api/logs')
    ElMessage.success('所有请求记录已清空')
    fetchLogs()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('清空请求日志失败:', error)
      ElMessage.error('清空请求日志失败')
    }
  }
}

// 处理行点击
const handleRowClick = (row) => {
  viewLogDetail(row.id)
}

// 处理分页
const handlePageChange = (page) => {
  currentPage.value = page
  // 实际项目中可能需要调用API进行分页查询
  // 这里简单模拟
}

onMounted(() => {
  fetchLogs()
})
</script>

<style scoped>
.request-logs-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.logs-card {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style>